package net.m510.autosurfer.saison;

import java.net.URI;
import java.util.logging.Logger;

import net.m510.autosurfer.common.DocumentGetProcess;
import net.m510.autosurfer.common.exception.InvalidDocumentException;
import net.m510.autosurfer.core.DocumentChecker;
import net.m510.autosurfer.core.exception.UserProcessException;

import org.apache.http.HttpHost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SaisonLogout extends DocumentGetProcess implements DocumentChecker {
	private static final Logger log = Logger.getLogger(SaisonLogout.class.getName());

	public SaisonLogout() {
		this(null,null);
	}
	
	public SaisonLogout(CloseableHttpClient client,HttpClientContext context) {
		super(client, context);
		super.log = log;
	}

	@Override
	protected URI getUri(Document doc) {
		// ログアウトタグからログアウト用URLを取り出す
		final String LOGOUT_ID="logOut";
		Element e = doc.getElementById(LOGOUT_ID);
		if ( e == null ) throw new InvalidDocumentException("id "+LOGOUT_ID+"が見つかりません",doc);
		Elements a = e.getElementsByTag("a");
		if ( a == null ) throw new InvalidDocumentException("ログアウト用のaタグが見つかりません",doc);
		String pathquery = a.first().attr("href");
		HttpHost host = context.getTargetHost();
		URI uri = URI.create(host.toURI());
		uri = uri.resolve(pathquery);
		return uri;
	}

	@Override
	public void check(Document doc) throws UserProcessException {
		final String LOGOUT_STR="ログアウトいたしました。";
		if ( doc.html().contains(LOGOUT_STR) ) return;
		throw new InvalidDocumentException("text "+LOGOUT_STR+" not found",doc);
	}

}
